package com.neusoft.grid.controller;

import com.neusoft.grid.entity.Grid;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

import java.io.*;
import java.net.URL;
import java.util.Map;
import java.util.Objects;

public class GridLoginViewController {

    @FXML
    private Button LoginButton;

    @FXML
    private TextField txt_password;

    @FXML
    private TextField txt_phoneNumber;

    @FXML
    void Login(ActionEvent event) {
        String phoneNumber = txt_phoneNumber.getText();
        String password = txt_password.getText();

        try {
            File file = new File("src/com/neusoft/grid/data/grid.txt");
            if (!file.exists() || file.length() == 0) {
                System.out.println("Data file missing or empty");
                return;
            }

            try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
                Map<String, Grid> gridMap = (Map<String, Grid>) ois.readObject();

                if (!gridMap.containsKey(phoneNumber)) {
                    System.out.println("User not found.");
                    return;
                }

                Grid u = gridMap.get(phoneNumber);
                if (!Objects.equals(password, u.getPassword())) {
                    System.out.println("Password error.");
                    return;
                }

                System.out.println("Login complete.");
                Stage stage = (Stage) LoginButton.getScene().getWindow();
                URL url = getClass().getResource("/com/neusoft/grid/view/GridMissionView.fxml");
                if (url == null) {
                    throw new IOException("FXML file not found");
                }

                FXMLLoader loader = new FXMLLoader(url);
                Parent root = loader.load();

                GridMissionViewController controller = loader.getController();
                controller.refreshMissionList();

                stage.setScene(new Scene(root));
                stage.setTitle("环境公众监督平台网格员工作页面");
            }
        } catch (ClassNotFoundException e) {
            System.err.println("Class mismatch in serialized data");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("Error loading data or FXML");
            e.printStackTrace();
        }
    }
}
